package com.java.androidmarket.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * description:
 * author:张腾
 * date:2021-04-23
 */
public class JWTUtils {
    private static final String SIGN = "!Q*,@#ey.t^x?";

    /**
     * 生成token
     * header.payload.signature
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,2);  //默认两天过期

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * 验证token合法性
     * 若token有异常会抛出
     * 无异常则获取token中的信息
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }


    /**
     * 从token中获取用户id
     * @param token
     * @return
     */
    public static String DecodedGetID(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String userId = verify.getClaim("userId").asString();
        return userId;
    }
}
